import React from 'react';
import { Form, Input, Icon, Checkbox, Radio, Button, Row, Col, Select, Card, InputNumber } from 'antd';
import { connect } from 'dva';

import styles from './index.less';
const namespace = 'returnRoules';
const { Option } = Select;
/**
 *  登录界面
 */
@connect(({ loading, returnRoules }) => ({
  rouleId: returnRoules.rouleId,
  getAllStateList: returnRoules.getAllStateList,
  rulesDetail: returnRoules.rulesDetail,
  //控制状态，绑定事件
  submitting: loading.effects['login/doLogin']
}))
@Form.create()
class StepThree extends React.Component {
  state = {
    checked1: false,
    checked2: false,
    checked3: false,
    paymentValue: 'No',
    freight: '', //运费,
    serviceFee1: '', //服务费
    serviceFee2: '', //服务费
    serviceFee3: '', //服务费
    damageCompensation1: '',
    damageCompensation2: '',
    damageCompensation3: '',
    restockFee: '',
    optionKey: '', //选中的select
    statesList: [
      {
        stats: '',
        costs: 0
      }
    ], //地址列表
    selectAreas: 0 //是否选中地址
  };

  onChange = value => {
    console.log('changed', value);
  };

  // 保存数据
  handleSubmit = (e, type) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const {
          serviceFee1,
          serviceFee2,
          serviceFee3,
          restockFee1,
          restockFee2,
          restockFee3,
          damageCompensation1,
          damageCompensation2,
          damageCompensation3
        } = this.state;
        // const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        const { statesList } = this.state;
        const { rulesDetail } = this.props;
        let serviceFee = '';
        let particularAreas = '';
        if (values.additionalCosts) {
          values.additionalCosts.map(item => {
            if (item == 'checked1') {
              serviceFee += item + '-' + serviceFee1 + ',';
            } else if (item == 'checked2') {
              serviceFee += item + '-' + serviceFee2 + ',';
            } else {
              serviceFee += item + '-' + serviceFee3 + ',';
            }
            // serviceFee+=item+"-"+freights+","
          });
          values.additionalCosts = serviceFee;
        }
        statesList.map((b, index) => {
          const stats = b.stats;
          if (stats) {
            if (index === statesList.length - 1) {
              particularAreas += stats + '-$' + b.costs;
            } else {
              particularAreas += stats + '-$' + b.costs + ',';
            }
          }
        });
        values.resetReturnFee =
          (restockFee1 && '1-' + restockFee1) ||
          (restockFee2 && '2-' + restockFee2) ||
          (restockFee3 && '3-' + restockFee3);
        values.damageCompensation =
          (damageCompensation1 && '1-' + damageCompensation1) ||
          (damageCompensation2 && '2-' + damageCompensation2) ||
          (damageCompensation3 && '3-' + damageCompensation3);
        values.particularAreas = particularAreas;
        delete values.restockFee1;
        delete values.restockFee2;
        delete values.restockFee3;
        delete values.damageCompensation1;
        delete values.damageCompensation2;
        delete values.damageCompensation3;
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        // if (type === "save") {
        //   this.props.dispatch({
        //     type: `${namespace}/save`,
        //     payload: {
        //       rulesDetail: values
        //     }
        //   });
        // } else {
        //   this.props.dispatch({
        //     type: `${namespace}/save`,
        //     payload: {
        //       stepCurrent: 3,
        //       rulesDetail: values
        //     }
        //   });
        //   this.props.dispatch({
        //     type: `${namespace}/getAllServiceProvider`
        //   })
        // }
        this.props.dispatch({
          type: `${namespace}/update`,
          payload: {
            shopsId: userInfo.shopsId,
            id: rulesDetail ? rulesDetail.id : this.props.rouleId,
            ...values
          },
          callback: () => {
            if (type === 'save') return;
            this.props.dispatch({
              type: `${namespace}/save`,
              payload: {
                stepCurrent: 3
              }
            });
            this.props.dispatch({
              type: `${namespace}/getAllServiceProvider`
            });
          }
        });
      }
    });
  };
  render() {
    const { selectAreas, statesList, serviceFee3, serviceFee2 } = this.state;
    const { getFieldDecorator } = this.props.form;
    const {
      checked2,
      checked3,
      freight,
      damageCompensation1,
      damageCompensation2,
      damageCompensation3,
      restockFee1,
      restockFee2,
      restockFee3
    } = this.state;
    const { getAllStateList, rulesDetail } = this.props;
    const selectedRe =
      rulesDetail && rulesDetail.returnLocation
        ? rulesDetail.returnLocation.indexOf(',') > -1
          ? rulesDetail.returnLocation.split(',').filter(a => a !== '')
          : [rulesDetail.returnLocation]
        : [];
    const particularAreas =
      rulesDetail && rulesDetail.particularAreas && rulesDetail.particularAreas.indexOf(',') > -1
        ? rulesDetail.particularAreas.split(',')
        : rulesDetail && rulesDetail.particularAreas
        ? [rulesDetail.particularAreas]
        : [];
    const additionalCosts =
      rulesDetail && rulesDetail.additionalCosts && rulesDetail.additionalCosts.indexOf(',') > -1
        ? rulesDetail.additionalCosts.split(',')
        : [];
    return (
      <div className={styles.stepThree}>
        <Form onSubmit={this.handleSubmit}>
          <Card title="Setup the return cost" bordered={false}>
            <Form.Item label="Please choose the packing fee standard">
              {getFieldDecorator('packingCharge', {
                rules: [{ required: true, message: 'Please Select packingCharge!' }],
                initialValue: rulesDetail && rulesDetail.packingCharge === 2 ? 2 : 1
              })(
                <Radio.Group value={this.state.value}>
                  <Radio value={1}>Per piece</Radio>
                  <Radio value={2}>Per order</Radio>
                </Radio.Group>
              )}
            </Form.Item>
            <Form.Item label="Standard return shipping cost">
              {getFieldDecorator('freights', {
                rules: [{ required: true, message: 'Please Select packingCharge!' }],
                initialValue: rulesDetail && rulesDetail.freight ? 1 : ''
              })(
                <Radio.Group
                  onChange={value => {
                    this.setState({
                      freight: value
                    });
                  }}
                >
                  <Radio value={1}>Curbside or threshold pickup</Radio>
                </Radio.Group>
              )}
            </Form.Item>
            {(freight || (rulesDetail && rulesDetail.freight)) && (
              <Form.Item label="" style={{ width: '30%' }}>
                {getFieldDecorator('freight', {
                  rules: [{ required: true, message: 'Please Select freight!' }],
                  initialValue: rulesDetail ? rulesDetail.freight : ''
                })(<Input prefix="$" suffix="" style={{ width: '100%' }} />)}
              </Form.Item>
            )}
            <div className="statesCost">
              <h3>Cost for special areas (optional)</h3>
              <Form.Item>
                <Radio.Group
                  value={selectAreas || (rulesDetail && rulesDetail.particularAreas ? 1 : '')}
                  onChange={value => {
                    this.setState({
                      selectAreas: value.target.value,
                      statesList: [
                        {
                          stats: '',
                          costs: 0
                        }
                      ]
                    });
                  }}
                >
                  <Radio value={1}>Curbside or threshold pickup</Radio>
                </Radio.Group>
              </Form.Item>
              {particularAreas.length > 0
                ? particularAreas.map((ditem, index) => {
                    //回显
                    return (
                      <div className="costList" key={index}>
                        <Form.Item label="State">
                          <Select
                            style={{ width: '30%' }}
                            onChange={value => {
                              this.state.statesList[index].states = value;
                              this.setState({
                                statesList: this.state.statesList
                              });
                            }}
                            value={ditem.states || ditem.split('-')[0]}
                            onFocus={() => {
                              this.props.dispatch({
                                type: `${namespace}/getAllStateList`
                              });
                            }}
                          >
                            {getAllStateList.length > 0 &&
                              getAllStateList.map(item => (
                                <Option
                                  key={item.abbreviation}
                                  disabled={
                                    selectedRe.filter(a => {
                                      if (a.indexOf(item.abbreviation) > -1) {
                                        return a;
                                      }
                                    }).length > 0
                                      ? true
                                      : false
                                  }
                                >
                                  {item.abbreviation}
                                </Option>
                              ))}
                          </Select>
                        </Form.Item>
                        <div className="line"></div>
                        <Form.Item label="Costs">
                          <InputNumber
                            min={0}
                            value={ditem.costs || ditem.split('-')[1]}
                            onChange={value => {
                              this.state.statesList[index].costs = value;
                              this.setState({
                                statesList: this.state.statesList
                              });
                            }}
                            tyle={{ width: '30%' }}
                          />
                        </Form.Item>
                        <Icon
                          type="delete"
                          onClick={(ditem, index) => {
                            this.state.statesList.splice(index, 1);
                            this.setState({
                              statesList: this.state.statesList,
                              selectAreas: this.state.statesList.length === 0 ? 0 : this.state.selectAreas
                            });
                          }}
                        />
                      </div>
                    );
                  })
                : selectAreas == 1 &&
                  statesList.map((ditem, index) => {
                    return (
                      <div className="costList" key={index}>
                        <Form.Item label="State">
                          <Select
                            onChange={value => {
                              console.log(value, 'value');
                              this.state.statesList[index].states = value;
                              this.setState({
                                statesList: this.state.statesList
                              });
                            }}
                            value={ditem.states}
                            onFocus={() => {
                              this.props.dispatch({
                                type: `${namespace}/getAllStateList`
                              });
                            }}
                          >
                            {getAllStateList.length > 0 &&
                              getAllStateList.map(item => (
                                <Option
                                  key={item.abbreviation}
                                  disabled={
                                    selectedRe.filter(a => {
                                      if (a.indexOf(item.abbreviation) > -1) {
                                        return a;
                                      }
                                    }).length > 0
                                      ? true
                                      : false
                                  }
                                >
                                  {item.abbreviation}
                                </Option>
                              ))}
                          </Select>
                        </Form.Item>
                        <div className="line"></div>
                        <Form.Item label="Costs">
                          <InputNumber
                            style={{ width: '100%' }}
                            min={0}
                            value={ditem.costs}
                            onChange={value => {
                              this.state.statesList[index].costs = value;
                              this.setState({
                                statesList: this.state.statesList
                              });
                            }}
                          />
                        </Form.Item>
                        <Icon
                          type="delete"
                          onClick={(ditem, index) => {
                            this.state.statesList.splice(index, 1);
                            this.setState({
                              statesList: this.state.statesList,
                              selectAreas: this.state.statesList.length === 0 ? 0 : this.state.selectAreas
                            });
                          }}
                        />
                      </div>
                    );
                  })}
              {((selectAreas == 1 && statesList.length > 0) || particularAreas.length > 0) && (
                <Button
                  type="primary"
                  onClick={() => {
                    this.state.statesList.push({
                      stats: '',
                      costs: 0
                    });
                    this.setState({
                      statesList: this.state.statesList
                    });
                  }}
                >
                  add states
                </Button>
              )}
            </div>
            <h3 style={{ margin: '15px 0' }}>Fee calculation without original package</h3>
            {rulesDetail &&
              rulesDetail.originalPackingCharge === 'Accept returns with no original package with charge' && (
                <Form.Item label="If the return has no original package, please set packing fee">
                  {getFieldDecorator('packingCost', {
                    rules: [{ required: false, message: 'Please input packingCost!' }],
                    initialValue: rulesDetail ? rulesDetail.packingCost : 1
                  })(<InputNumber min={0} />)}
                </Form.Item>
              )}
          </Card>
          <Card title="Additional service charge (optional)" bordered={false}>
            <Form.Item label="">
              {getFieldDecorator('additionalCosts', {
                rules: [{ required: false, message: 'Please checked additionalCosts!' }],
                initialValue: rulesDetail ? rulesDetail.additionalCosts : ''
              })(
                <Checkbox.Group
                  style={{ width: '100%' }}
                  onChange={checkedValues => {
                    this.setState({
                      checked1: false,
                      checked2: false,
                      checked3: false
                    });
                    checkedValues.length > 0
                      ? checkedValues.map(item => {
                          if (item === 'checked1') {
                            this.setState({
                              checked1: true
                            });
                          } else if (item === 'checked2') {
                            this.setState({
                              checked2: true
                            });
                          } else if (item === 'checked3') {
                            this.setState({
                              checked3: true
                            });
                          }
                        })
                      : this.setState({
                          checked1: false,
                          checked2: false,
                          checked3: false
                        });
                  }}
                >
                  {/* serviceFee */}
                  <Row gutter={20}>
                    <Col span={12}>
                      <Checkbox value="checked2">Indoor pick-up</Checkbox>
                      {(checked2 || additionalCosts.filter(a => a.indexOf('checked2') > -1).length > 0) && (
                        <InputNumber
                          placeholder="$"
                          value={
                            additionalCosts.filter(a => a.indexOf('checked2') > -1).length > 0
                              ? Number(additionalCosts.filter(a => a.indexOf('checked2') > -1)[0].split('-')[1])
                              : serviceFee2
                          }
                          onChange={value => {
                            this.setState({
                              serviceFee2: value
                            });
                          }}
                          prefix="$"
                          suffix=""
                          style={{ width: '100%' }}
                        />
                      )}
                    </Col>
                    <Col span={12}>
                      <Checkbox value="checked3">Indoor pick-up and packing</Checkbox>
                      {(checked3 || additionalCosts.filter(a => a.indexOf('checked3') > -1).length > 0) && (
                        <InputNumber
                          placeholder="$"
                          value={
                            additionalCosts.filter(a => a.indexOf('checked2') > -1).length > 0
                              ? Number(additionalCosts.filter(a => a.indexOf('checked3') > -1)[0].split('-')[1])
                              : serviceFee3
                          }
                          onChange={value => {
                            this.setState({
                              serviceFee3: value
                            });
                          }}
                          prefix="$"
                          suffix=""
                          style={{ width: '100%' }}
                        />
                      )}
                    </Col>
                  </Row>
                </Checkbox.Group>
              )}
            </Form.Item>
          </Card>
          <Card title="Payment" bordered={false}>
            <Form.Item label="Only orginal credit can be accepted . If No is chosen, store credit will be issued">
              {getFieldDecorator('payType', {
                rules: [{ required: true, message: 'Please Select payType!' }],
                initialValue: rulesDetail ? rulesDetail.payType : 1
              })(
                <Radio.Group style={{ width: '100%' }}>
                  <Row>
                    <Col span={4}>
                      <Radio value={1}>Yes</Radio>
                    </Col>
                    <Col span={4}>
                      <Radio value={2}>No</Radio>
                    </Col>
                  </Row>
                </Radio.Group>
              )}
            </Form.Item>
          </Card>
          {/* <Card title="Gift card（optional）" bordered={false}>
            <Form.Item label="Gift card can be refunded" style={{ width: '30%' }}>
              {getFieldDecorator('gitReturn', {
                rules: [{ required: false, message: 'Please Select gitReturn!' }],
                initialValue: rulesDetail ? rulesDetail.gitReturn : 'No',
              })(
                <Radio.Group style={{ width: '100%' }} value={paymentValue} onChange={(value) => {
                  this.setState({
                    paymentValue: value.target.value
                  })
                }}>
                  <Row>
                    <Col span={4}>
                      <Radio value="Yes" >Yes</Radio>
                    </Col>
                    <Col span={4}>
                      <Radio value="No" >No</Radio>
                    </Col>
                  </Row>
                </Radio.Group>
              )}
            </Form.Item>
            {
              paymentValue === 'Yes' && <Form.Item label="Repayment method" style={{ width: '30%' }} >
                {getFieldDecorator('payType', {
                  rules: [{ required: true, message: 'Please Select payType!' }],
                  initialValue: rulesDetail ? rulesDetail.payType : 1
                })(
                  <Select
                    placeholder="Please select"
                    onChange={this.handleSelectChange}
                  >
                    <Option value={2}>integral</Option>
                    <Option value={1}>card</Option>
                  </Select>
                )}
              </Form.Item>
            }

          </Card> */}

          <Card title="Restocking fee" bordered={false}>
            <Form.Item label="" style={{ width: '30%' }}>
              {getFieldDecorator('restockFee1', {
                initialValue:
                  rulesDetail && rulesDetail.resetReturnFee && rulesDetail.resetReturnFee.split('-')[0] == 1
                    ? rulesDetail.resetReturnFee.split('-')[1]
                    : ''
              })(
                <InputNumber
                  disabled={restockFee2 || restockFee3}
                  onChange={value => {
                    this.setState({
                      restockFee1: value
                    });
                  }}
                  min={0}
                />
              )}
              <span className={styles.txt}> % of good value</span>
            </Form.Item>
            <Form.Item label="" style={{ width: '30%' }}>
              {getFieldDecorator('restockFee2', {
                initialValue:
                  rulesDetail && rulesDetail.resetReturnFee && rulesDetail.resetReturnFee.split('-')[0] == 2
                    ? rulesDetail.resetReturnFee.split('-')[1]
                    : ''
              })(
                <InputNumber
                  disabled={restockFee1 || restockFee3}
                  onChange={value => {
                    this.setState({
                      restockFee2: value
                    });
                  }}
                  min={0}
                />
              )}
              <span className={styles.txt}> % of good value + tax</span>
            </Form.Item>
            <Form.Item label="" style={{ width: '40%' }}>
              {getFieldDecorator('restockFee3', {
                initialValue:
                  rulesDetail && rulesDetail.resetReturnFee && rulesDetail.resetReturnFee.split('-')[0] == 3
                    ? rulesDetail.resetReturnFee.split('-')[1]
                    : ''
              })(
                <InputNumber
                  disabled={restockFee2 || restockFee1}
                  onChange={value => {
                    this.setState({
                      restockFee3: value
                    });
                  }}
                  min={0}
                />
              )}
              <span className={styles.txt}> % of good value + tax + delivery fee</span>
            </Form.Item>
          </Card>
          <Card title="Damaged goods" bordered={false}>
            <Form.Item label="" style={{ width: '30%' }}>
              {getFieldDecorator('damageCompensation1', {
                rules: [{ required: false, message: 'Please Select packingCharge!' }],
                initialValue:
                  rulesDetail && rulesDetail.damageCompensation && rulesDetail.damageCompensation.split('-')[0] == 1
                    ? rulesDetail.damageCompensation.split('-')[1]
                    : ''
              })(
                <InputNumber
                  disabled={damageCompensation2 || damageCompensation3}
                  onChange={value => {
                    this.setState({
                      damageCompensation1: value
                    });
                  }}
                  min={0}
                  max={10000000000000}
                />
              )}
              <span className={styles.txt}> % of good value</span>
            </Form.Item>
            <Form.Item label="" style={{ width: '30%' }}>
              {getFieldDecorator('damageCompensation2', {
                rules: [{ required: false, message: 'Please Select packingCharge!' }],
                initialValue:
                  rulesDetail && rulesDetail.damageCompensation && rulesDetail.damageCompensation.split('-')[0] == 1
                    ? rulesDetail.damageCompensation.split('-')[1]
                    : ''
              })(
                <InputNumber
                  disabled={damageCompensation1 || damageCompensation3}
                  onChange={value => {
                    this.setState({
                      damageCompensation2: value
                    });
                  }}
                  min={0}
                  max={10000000000000}
                />
              )}
              <span className={styles.txt}> % of good value + tax</span>
            </Form.Item>
            <Form.Item label="" style={{ width: '40%' }}>
              {getFieldDecorator('damageCompensation3', {
                rules: [{ required: false, message: 'Please Select packingCharge!' }],
                initialValue:
                  rulesDetail && rulesDetail.damageCompensation && rulesDetail.damageCompensation.split('-')[0] == 1
                    ? rulesDetail.damageCompensation.split('-')[1]
                    : ''
              })(
                <InputNumber
                  disabled={damageCompensation1 || damageCompensation2}
                  onChange={value => {
                    this.setState({
                      damageCompensation3: value
                    });
                  }}
                  min={0}
                  max={10000000000000}
                />
              )}
              <span className={styles.txt}> % of good value + tax + delivery fee</span>
            </Form.Item>
          </Card>
          <Form.Item className={styles.btnList}>
            <Button onClick={e => this.handleSubmit(e, 'save')} className={styles.formBtn}>
              Save
            </Button>
            <Button htmlType="submit" className={styles.formBtn}>
              Next
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default StepThree;
